﻿using Contract.Domain;
using Contract.Infrastructure.Repository;
using Contract.WebApi.Application.Commands;
using MediatR;

namespace Contract.WebApi.Application.CommandHandler
{
    public class AlterStateCommandHandler : IRequestHandler<AlterStateCommands, int>
    {
        private readonly IRepository<Domain.Contract> repository;
        private readonly IRepository<Tail> tailRepository;

        public AlterStateCommandHandler(IRepository<Domain.Contract> repository, IRepository<Tail> tailRepository)
        {
            this.repository = repository;
            this.tailRepository = tailRepository;
        }

        public async Task<int> Handle(AlterStateCommands request, CancellationToken cancellationToken)
        {
            var info = await repository.GetAsync(x=>x.ContractId==request.Id);
            info.AuditState = request.AuditState;
            var ind = await repository.UpdateAsync(info);
            if (request.AuditState == 2)
            {
                Tail tail = new Tail();
                tail.DateTime = DateTime.Now;
                tail.Approver = "小明";
                tail.ShipperEnterprise = "广州禾誉物流有限公司";
                tail.TrackingState = "合同已审批";
                tail.ContractNumber = info.ContractNumber;
                await tailRepository.AddAsync(tail);
            }
            return ind;
        }
    }
}
